<template>
    <div>
        <van-sticky :offset-top="0">
            <van-nav-bar title="详情" left-text="返回" left-arrow @click-left="onClickLeft" />
        </van-sticky>

        <div class="top">
            <img :src=detail.src alt="">
            <p class="name">{{ detail.name }}</p>
            <p class="title">所需积分：{{ detail.integral }}</p>
            <p>使用日期：{{ detail.date }}</p>
            <p>数量：{{ detail.amount }}</p>
        </div>



        <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
        </van-divider>
        <div class="bottom">
            <p>使用需知:</p>
            <span class="content">1、产品以餐厅食物为准</span><br>
            <span class="content">2、兑换成功后,扣除的积分不予退还</span><br>
            <span class="content">3、每个用户只能兑换一次</span>
        </div>

        <van-button class="footerbtn" type="primary" size="large" v-on:click="convert" @click="handleCouponAdd">
            点击兑换
        </van-button>
    </div>



</template>

<script setup lang="ts">
import { useRoute } from 'vue-router';
import { computed, ref } from 'vue';
import 'vant/es/toast/style';
import { Toast } from 'vant';
import { useCoupon } from '../../store/Coupon'
const route = useRoute();
const detail = ref();
detail.value = route.query

// console.log(detail.value);

const photo = computed<Array<String>>(() => {
    let arr = []
    for (let attr in detail.value) {
        if (attr.indexOf('img') != -1) {
            // 动态键名
            arr.push(detail.value[attr])
        }
    }
    return arr
})
// console.log(photo);
const onClickLeft = () => history.back();


// 兑换积分
function convert() {
    let integrate: number = Number(localStorage.getItem("integrate"))
    // 接受数据包积分,并且提交到pinia
    let newIntegral: number = detail.value.integral;
    if ((integrate - newIntegral) >= 0) {
        integrate = integrate - newIntegral;
        detail.value.amount = detail.value.amount - 1
        localStorage.setItem("integrate", String(integrate))
        console.log(localStorage.getItem("integrate"))
        Toast('兑换成功');
    } else {
        Toast('积分不足');
    };
}

// 
const coupon = useCoupon()
const handleCouponAdd = () => {
    let integrate: number = Number(localStorage.getItem("integrate"))
    let newIntegral: number = detail.value.integral;
    let n = 0;
    if ((integrate - newIntegral) >= 0)
        // 接受数据包积分,并且提交到pinia
        n++
    coupon.couponAddAction({
        ...detail.value,
        number: n
    })
}

</script>

<style lang="scss" scoped>
.top {
    margin-top: 10rem;
    margin-left: 10rem;
}

.top>img {
    width: 100%;
    height: 70rem;
    margin-left: -5rem;
}

.name {
    font-size: 6rem;
}

.title {
    font-size: 4rem;
}

.content {
    font-size: 4rem;
}

.bottom {
    margin-top: 10rem;
}

.bottom>.content {
    font-size: 1.5rem;
    color: gray;
}

.content {
    margin-left: 10rem;
}

.footerbtn {
    margin-top: 10rem;

}
</style>